package admin

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type SpecTemplateInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSpecTemplateInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SpecTemplateInfoLogic {
	return &SpecTemplateInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SpecTemplateInfoLogic) SpecTemplateInfo(req *types.IdForm) (resp *types.SpecTemplateResp, err error) {
	data := &models.SpecTemplate{}
	if !utils.GetDataById(req.Id, data) {
		return nil, errors.New("规格模板不存在")
	}
	resp = &types.SpecTemplateResp{}
	copier.Copy(resp, data)

	resp.Specs = make([]types.SpecKeyItem, 0)

	// 规格模板值
	specValues := make([]types.SpecValueItem, 0)
	specValueTx := utils.Db.Model(&models.SpecValue{}).Where("spec_template_id = ?", data.ID).Order("spec_key_id DESC,id desc")
	utils.TxFind(specValueTx, &specValues)

	specValuesMap := make(map[uint][]types.SpecValueItem)
	for _, v := range specValues {
		specValuesMap[v.SpecKeyID] = append(specValuesMap[v.SpecKeyID], v)
	}

	// 规格模板值
	specKeys := make([]models.SpecKey, 0)
	specTx := utils.Db.Model(&models.SpecKey{}).Where("spec_template_id = ?", data.ID).Order("id desc")
	utils.TxFind(specTx, &specKeys)

	for _, v := range specKeys {
		item := types.SpecKeyItem{}
		copier.Copy(&item, &v)
		if value, ok := specValuesMap[v.ID]; ok {
			item.Values = value
		} else {
			item.Values = make([]types.SpecValueItem, 0)
		}
		resp.Specs = append(resp.Specs, item)
	}

	return resp, nil
}
